"""
跑腿代办模型
包含外卖代拿、快递代取、小事代办等功能
"""

from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone

User = get_user_model()


class ErrandRunner(models.Model):
    """
    跑腿员模型
    存储跑腿员的基本信息
    """
    
    # 跑腿员状态选择
    STATUS_CHOICES = [
        ('active', '活跃'),
        ('busy', '忙碌'),
        ('offline', '离线'),
        ('suspended', '暂停'),
        ('banned', '已封禁'),
    ]
    
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name='errand_runner',
        verbose_name='用户'
    )
    
    # 跑腿员信息
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='offline',
        verbose_name='跑腿员状态'
    )
    
    is_verified = models.BooleanField(
        default=False,
        verbose_name='是否认证'
    )
    
    # 服务信息
    service_areas = models.JSONField(
        default=list,
        verbose_name='服务区域'
    )
    
    service_types = models.JSONField(
        default=list,
        verbose_name='服务类型'
    )
    
    # 统计信息
    total_orders = models.IntegerField(
        default=0,
        verbose_name='总订单数'
    )
    
    completed_orders = models.IntegerField(
        default=0,
        verbose_name='完成订单数'
    )
    
    cancelled_orders = models.IntegerField(
        default=0,
        verbose_name='取消订单数'
    )
    
    total_earnings = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=0.00,
        verbose_name='总收入'
    )
    
    rating = models.DecimalField(
        max_digits=3,
        decimal_places=2,
        default=5.00,
        verbose_name='评分'
    )
    
    # 时间信息
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='注册时间'
    )
    
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name='更新时间'
    )
    
    class Meta:
        verbose_name = '跑腿员'
        verbose_name_plural = '跑腿员'
        db_table = 'errand_runners'
    
    def __str__(self):
        return f"{self.user.username} - {self.get_status_display()}"


class ErrandOrder(models.Model):
    """
    跑腿订单模型
    存储跑腿订单的详细信息
    """
    
    # 订单类型选择
    ORDER_TYPE_CHOICES = [
        ('takeout', '外卖代拿'),
        ('express', '快递代取'),
        ('errand', '小事代办'),
        ('other', '其他'),
    ]
    
    # 订单状态选择
    STATUS_CHOICES = [
        ('pending', '待接单'),
        ('accepted', '已接单'),
        ('in_progress', '进行中'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
        ('disputed', '争议中'),
    ]
    
    # 基础信息
    order_number = models.CharField(
        max_length=20,
        unique=True,
        verbose_name='订单号'
    )
    
    customer = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='errand_orders',
        verbose_name='客户'
    )
    
    runner = models.ForeignKey(
        ErrandRunner,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='orders',
        verbose_name='跑腿员'
    )
    
    # 订单类型和状态
    order_type = models.CharField(
        max_length=20,
        choices=ORDER_TYPE_CHOICES,
        verbose_name='订单类型'
    )
    
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='pending',
        verbose_name='订单状态'
    )
    
    # 订单详情
    title = models.CharField(
        max_length=200,
        verbose_name='订单标题'
    )
    
    description = models.TextField(
        verbose_name='订单描述'
    )
    
    # 地址信息
    pickup_address = models.CharField(
        max_length=200,
        verbose_name='取货地址'
    )
    
    delivery_address = models.CharField(
        max_length=200,
        verbose_name='送货地址'
    )
    
    # 联系信息
    customer_phone = models.CharField(
        max_length=11,
        verbose_name='客户电话'
    )
    
    # 费用信息
    base_fee = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        verbose_name='基础费用'
    )
    
    tip_fee = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=0.00,
        verbose_name='小费'
    )
    
    total_fee = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        verbose_name='总费用'
    )
    
    # 时间信息
    expected_pickup_time = models.DateTimeField(
        verbose_name='期望取货时间'
    )
    
    expected_delivery_time = models.DateTimeField(
        verbose_name='期望送达时间'
    )
    
    accepted_at = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name='接单时间'
    )
    
    completed_at = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name='完成时间'
    )
    
    # 时间信息
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name='更新时间'
    )
    
    class Meta:
        verbose_name = '跑腿订单'
        verbose_name_plural = '跑腿订单'
        db_table = 'errand_orders'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.order_number} - {self.title}"


class OrderMessage(models.Model):
    """
    订单消息模型
    存储订单相关的聊天消息
    """
    
    order = models.ForeignKey(
        ErrandOrder,
        on_delete=models.CASCADE,
        related_name='messages',
        verbose_name='订单'
    )
    
    sender = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='sent_messages',
        verbose_name='发送者'
    )
    
    content = models.TextField(
        verbose_name='消息内容'
    )
    
    message_type = models.CharField(
        max_length=20,
        default='text',
        verbose_name='消息类型'
    )
    
    is_read = models.BooleanField(
        default=False,
        verbose_name='是否已读'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='发送时间'
    )
    
    class Meta:
        verbose_name = '订单消息'
        verbose_name_plural = '订单消息'
        db_table = 'errand_messages'
        ordering = ['created_at']
    
    def __str__(self):
        return f"{self.order.order_number} - {self.sender.username}"


class OrderRating(models.Model):
    """
    订单评价模型
    客户对跑腿服务的评价
    """
    
    order = models.OneToOneField(
        ErrandOrder,
        on_delete=models.CASCADE,
        related_name='rating',
        verbose_name='订单'
    )
    
    customer = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='given_ratings',
        verbose_name='评价客户'
    )
    
    runner = models.ForeignKey(
        ErrandRunner,
        on_delete=models.CASCADE,
        related_name='received_ratings',
        verbose_name='被评价跑腿员'
    )
    
    # 评价信息
    rating = models.IntegerField(
        choices=[(i, i) for i in range(1, 6)],
        verbose_name='评分'
    )
    
    comment = models.TextField(
        blank=True,
        verbose_name='评价内容'
    )
    
    # 评价维度
    service_quality = models.IntegerField(
        choices=[(i, i) for i in range(1, 6)],
        verbose_name='服务质量'
    )
    
    delivery_speed = models.IntegerField(
        choices=[(i, i) for i in range(1, 6)],
        verbose_name='配送速度'
    )
    
    communication = models.IntegerField(
        choices=[(i, i) for i in range(1, 6)],
        verbose_name='沟通态度'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='评价时间'
    )
    
    class Meta:
        verbose_name = '订单评价'
        verbose_name_plural = '订单评价'
        db_table = 'errand_ratings'
    
    def __str__(self):
        return f"{self.order.order_number} - {self.rating}星"


class ServiceArea(models.Model):
    """
    服务区域模型
    定义跑腿服务的区域范围
    """
    
    name = models.CharField(
        max_length=100,
        unique=True,
        verbose_name='区域名称'
    )
    
    description = models.TextField(
        blank=True,
        verbose_name='区域描述'
    )
    
    is_active = models.BooleanField(
        default=True,
        verbose_name='是否启用'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    
    class Meta:
        verbose_name = '服务区域'
        verbose_name_plural = '服务区域'
        db_table = 'errand_service_areas'
        ordering = ['name']
    
    def __str__(self):
        return self.name


class ServiceType(models.Model):
    """
    服务类型模型
    定义跑腿服务的类型
    """
    
    name = models.CharField(
        max_length=50,
        unique=True,
        verbose_name='服务类型名称'
    )
    
    description = models.TextField(
        blank=True,
        verbose_name='服务描述'
    )
    
    base_price = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        verbose_name='基础价格'
    )
    
    icon = models.CharField(
        max_length=50,
        blank=True,
        verbose_name='服务图标'
    )
    
    is_active = models.BooleanField(
        default=True,
        verbose_name='是否启用'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    
    class Meta:
        verbose_name = '服务类型'
        verbose_name_plural = '服务类型'
        db_table = 'errand_service_types'
        ordering = ['name']
    
    def __str__(self):
        return self.name
